package com.oracle.common;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @program: CampusMatching
 * @description: 文件·处理
 * @author: zhaolei
 * @create: 2020-07-31 19:45
 **/
@Component
public class FileProcess {

    public  String  getVirtualPath(MultipartFile file) {
        if (file == null) {
            System.out.println("图片为空");
            return  null;
        } else {
            //获取文件上传的根目录 D:\temp2/img
            String path = Constant.UPLOAD_PATH + Constant.IMG_FILE_NAME;
            // 获取上传文件名
            String filename = file.getOriginalFilename();
            // 重新拼接文件名字
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String saveName = null;
            if (filename.contains(".")) {
                saveName = uuid + "." + filename.substring(filename.lastIndexOf(".") + 1, filename.length());
            } else {
                saveName = "";
            }
            //保存
            try {
                // 验证路径
                File targetFile = new File(path);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                //将图片转移到指定位置
                file.transferTo(new File(path + "/" + saveName).getAbsoluteFile());
            } catch (IOException e) {
                e.printStackTrace();
            }
            //相对路径
            String filePath = Constant.VIRTUAL_IMG_PATH;
            System.out.println(filePath + "/" + saveName);
            return filePath + "/" + saveName;
        }
    }


}


